package cn.li.security.service;


import cn.li.security.entity.Account;
import cn.li.security.repository.AccountRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.stream.Collectors;


@Service
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private AccountRepository accountRepository;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Account account = accountRepository.findByUsername(username);
        if(account == null ){
            throw new UsernameNotFoundException(username + " not found");
        }
        return covertFromAccount(account);
    }

    /**
     * 转换成userdetail
     * @param account
     * @return
     */
    private User covertFromAccount(Account account){
        User u= new User(account.getUsername(),account.getPassword(),
                //这里简单的把角色封装成鉴权列表，实际应用应当结合业务需求，将role->authority进行多对多的关系，进而进行转换
                account.getRoles().stream().map(item->new SimpleGrantedAuthority(item))
                .collect(Collectors.toList())
        );
        return u;
    }
}
